package com.example.electricbicycle.controller;

import com.example.electricbicycle.po.Customer;
import com.example.electricbicycle.service.CustomerService;
import com.example.electricbicycle.service.CustomerServiceImpl;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "AddCustomerServlet", value = "/addcustomer")
public class AddCustomerServlet extends HttpServlet {
    private final CustomerService customerService = new CustomerServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idParam = request.getParameter("id");
        if (idParam != null && !idParam.isEmpty()) {
            int customerId = Integer.parseInt(idParam);
            Customer customer = customerService.getCustomerById(customerId);
            request.setAttribute("customer", customer);
        }
        request.getRequestDispatcher("/admin/addcustomer.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idParam = request.getParameter("id");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");

        Customer customer = new Customer();
        customer.setName(name);
        customer.setPhone(phone);
        customer.setAddress(address);

        if (idParam != null && !idParam.isEmpty()) {
            int customerId = Integer.parseInt(idParam);
            customer.setId(customerId);
            customerService.updateCustomer(customer);
            request.getSession().setAttribute("successMsg", "客户信息更新成功！");
        } else {
            customerService.addCustomer(customer);
            request.getSession().setAttribute("successMsg", "客户添加成功！");
        }

        response.sendRedirect(request.getContextPath() + "/CustomerListServlet");
    }
}